// import { login, logout, getInfo } from '@/api/user'
import { getLocalStorage, removeLocalStorage } from '@/utils/localStorage'
import { setHospitalCode } from '@/utils/utils'
import {
  userLogin,
  getUserByToken,
  loginByTokensm2,
  getSysUserUserMenuTreeAndRightList,
  getSysHospitalGetList,
  getSysUserHospitalList,
  getHospitalAppsettings,
  getexamnotice
} from '@/api/api.js'
import {
  getFileRead
} from '@/api/fileapi'
import {
  getCheckroomGroupListTree,
  getDefaultCheckRoomArr
} from '@/api/room'
import {
  getToken,
  setToken,
  setRefreshToken,
  removeToken,
  removeRefreshToken,
  setUserInfo,
  getUserInfo,
  removeUserInfo,
  setRefreshExpires,
  // getRefreshExpires,
  removeRefreshExpires,
  setExpires,
  // getExpires,
  removeExpires,
  setMenu,
  removeMenu,
  getTags,
  setTags,
  removeTags,
  getDefaultCheckRoom,
  setDefaultCheckRoom,
  // removeDefaultCheckRoom,
  getAppSetting,
  setAppSetting,
  removeAppSetting,
  getLogoutFlag,
  setLogoutFlag,
  removeLogoutFlag,
  setOperateTime,
  getOperateTime,
  removeOperateTime
} from '@/utils/auth'
import {
  hex_md5
} from '@/utils/md5.js'
import aes from '@/utils/aes'
import { setContinuityNum } from '@/utils/schedule'

import router from '@/router'
import MenuUtils from '@/utils/menuUtils.js'
import menuCorrect from '@/utils/menuCorrect.js'
import asyncMenu from '@/router/asyncMenu.js'
import menulistjson from '@/data/menulistjson.js'
import { sysAppId, isLocal } from '@/settings.js'
// import { resetRouter } from '@/router'
import avatar from '@/assets/images/avatar2.jpg'

import { setLocalStorage } from '@/utils/localStorage'
const _b = new aes.Base64()
const refreshTime = window.g.EXPIRE_TIME || 5
/**
 * 主键:id
 * 用户名:userName
 * 用户主键:userCode
 * 医院主键:hospitalId
 * 医院代码:hospitalCode
 * 医院名称:hospitalName
 * Token令牌 accessToken:token
 * Token令牌有效期 expires [auths]:tokenExpires
 * 部门主键:departmentId
 * 菜单
 */
const userInfo = getUserInfo() !== 'null' ? _b.decode(getUserInfo()) : {}
const localDefaultCheckRoom = getDefaultCheckRoom()
const appSetting = getAppSetting()
const getDefaultState = () => {
  return {
    userInfo: userInfo,
    userName: userInfo.userName,
    userCode: userInfo.userCode,
    avatar: avatar,
    userGrade: userInfo.userGrade,
    deptName: userInfo.deptName,
    hospitalCode: userInfo.hospitalCode,
    hospitalName: userInfo.hospitalName,
    depArea: userInfo.depArea,
    hisuid: userInfo.hisuid,
    userFlag: userInfo.userFlag,
    token: getToken(),
    tokenType: '',
    id: userInfo.id,
    // 页面按钮权限
    tags: getTags(),
    // 是否主责 一体化
    iszzYTH: false,
    // 默认选择机房查询 医院/院区/部门/科室/机房 数组
    checkRoomTree: [],
    checkRoom: localDefaultCheckRoom || [],
    appoContinuation: false,
    appSetting: appSetting || {},
    parametersValuesSplit: appSetting && appSetting.parametersValuesSplit ? appSetting.parametersValuesSplit : ',',
    pubcliKey: appSetting ? appSetting.pubcliKey : '',
    privateKey: appSetting ? appSetting.privateKey : '',
    parametersTypeByPart: appSetting ? appSetting.parametersTypeByPart : '',
    depSettings: appSetting ? appSetting.depSettings : '',
    appoRepair: !window.g.REPAIR_UO, // appoRepair 这个值是历史遗留下来的，若要该，关联影响可能会比较大，尽量在有问题的地方单独改，可取消对他的使用
    isContinuityNum: false,
    parametersTypeByPartKey1: appSetting && appSetting.isUpperBigpart ? 'BIGPART' : 'bigpart',
    parametersTypeByPartKey2: 'dengjipart',
    examnotice: '',
    clientIP: ''
  }
}

const state = getDefaultState()

const mutations = {
  SET_examnotice: (state, data) => {
    // let result = ''
    // if (data) {
    //   result = data // + `<p>1.你好</p><p>2.你好</p><p>3.你好</p>` // .replace('<p>', '').replace('</p>', '').replace('<p style= "white-space: normal;">', '').replace('<br style="white-space: normal;"/>', '').replace('&nbsp;', '').replace('</p><p>', '')
    // }
    state.examnotice = data
  },
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.userName = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_TOKENINFO: (state, info) => {
    state.token = info.accessToken
    state.tokenType = info.type
    // console.warn('JJYY_SET_TOKENINFO=>info', info)
    localStorage.setItem('JJYY_SET_TOKENINFO', JSON.stringify(info))
    // setLocalStorage('isCanSearchOrderedList', 1)
  },
  SET_USERINFO: (state, info) => {
    state.userInfo = info
    state.userName = info.userName
    state.userCode = info.userCode
    state.avatar = info.userPhoto ? info.userPhoto : avatar
    state.id = info.id
    state.hospitalCode = info.hospitalCode
    state.hospitalName = info.hospitalName
    state.deptName = info.deptName
    state.userGrade = info.userGrade
    state.depArea = info.depArea
    state.doctorCode = info.doctorCode
    state.hisuid = info.hisuid
    state.userFlag = info.userFlag
  },
  SET_APPSETTINGS: (state, info) => {
    state.appSetting = info
    state.parametersValuesSplit = info.parametersValuesSplit ? info.parametersValuesSplit : ','
    state.pubcliKey = info.pubcliKey
    state.privateKey = info.privateKey
    state.parametersTypeByPart = info.parametersTypeByPart
    state.depSettings = info.depSettings
    state.parametersTypeByPartKey1 = info.isUpperBigpart ? 'BIGPART' : 'bigpart'
    state.clientIP = info.clientIP
  },
  SET_TAGS: (state, tags) => {
    state.tags = tags
  },
  SET_ISCONTINUITYNUM: (state, isContinuityNum) => {
    state.isContinuityNum = isContinuityNum
  },
  SET_APPOCONTINUATION: (state, type) => {
    state.appoContinuation = type
  },
  SET_ISZZYTH: (state, iszz) => {
    state.iszzYTH = iszz
  },
  SET_ROOMTREE: (state, room) => {
    state.checkRoomTree = room
  },
  SET_DEFAULTROOM: (state, room) => {
    state.checkRoom = room
  }
}

const actions = {
  get_examnotice({
    commit,
    dispatch
  }, data) {
    const {HospitalCode, AccessNo} = data
    return new Promise((resolve, reject) => {
      getexamnotice({HospitalCode, AccessNo}).then(async response => {
        const {
          content
        } = response
        if (response) {
          commit('SET_examnotice', content || '无')
          resolve(content)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  set_token({
    commit,
    dispatch
  }, token) {
    commit('SET_TOKEN', token)
    setToken(token)
  },
  // 用户登录
  login({
    dispatch,
    commit
  }, userInfo) {
    setLogoutFlag(false)
    if (isLocal) {
      return new Promise(async (resolve, reject) => {
        await dispatch('loginLocal')
        resolve()
      })
    }
    const {
      account,
      password
    } = userInfo
    // console.error('来这里了嘛', getLogoutFlag())
    const pwd = window.g.PWDTYPE === 'AES' ? aes.AESEncrypt(password) : hex_md5(password).toUpperCase()
    return new Promise((resolve, reject) => {
      userLogin({
        userCode: account.trim(),
        userPwd: pwd,
        SysAppId: sysAppId
      }).then(async response => {
        if (response.code == 10000 || response.Code == 10000) {
          const {
            content
          } = response
          localStorage.removeItem('JJYY_SET_TOKENINFO')
          await dispatch('removeLocalInfo')
          commit('SET_TOKENINFO', content)
          setToken(content.accessToken)
          setRefreshToken(content.refreshToken)
          setExpires(content.expires)
          // 登录的时候设置客户端过期时间
          let refreshExpires = Date.parse(new Date()) / 1000 + refreshTime * 24 * 3600 // 换算成秒
          setRefreshExpires(refreshExpires)
          console.log('=============')
          await dispatch('getInfo')
          await dispatch('getMenu')
          console.log('登录成功-begin')
          resolve()
        } else {
          reject()
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 获取用户信息
  loginByTokensm2({
    commit,
    dispatch
  }, data) {
    return new Promise((resolve, reject) => {
      loginByTokensm2(data).then(async response => {
        const {
          content
        } = response
        if (response) {
          const {
            accessToken,
            expires,
            refreshToken
          } = content
          // console.warn('JJYY_SET_TOKENINFO=>content', content)
          commit('SET_TOKENINFO', content)
          setToken(accessToken)
          setExpires(expires)
          // 登录的时候设置客户端过期时间
          if (refreshToken) {
            setRefreshToken(refreshToken)
            let refreshExpires = Date.parse(new Date()) / 1000 + refreshTime * 24 * 3600 // 换算成秒
            setRefreshExpires(refreshExpires)
          }
          // 设置用户查询排班管理机房选择的默认机房选项
          // await dispatch('getDefaultCheckRoomTree')
          resolve(content)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 获取用户信息
  getInfo({
    commit,
    dispatch
  }) {
    return new Promise((resolve, reject) => {
      getUserByToken().then(async response => {
        const {
          content
        } = response
        // console.log('getUserByToken=>content', content)
        if (response) {
          let _avatarUrl = ''
          // content.hospitalCode = '47068178733038211A1001' // 乐清三医调试设置
          if (content.userPhoto) {
            getFileRead(content.userPhoto).then(data => {
              _avatarUrl = data
              content.userPhoto = _avatarUrl
              commit('SET_USERINFO', content)
              const info = JSON.stringify(content)
              setUserInfo(_b.encode(info))
            })
          }
          commit('SET_USERINFO', content)
          const info = JSON.stringify(content)
          setUserInfo(_b.encode(info))
          // await dispatch('removeLocalInfo')
          // 获取用户权限医院列表
          // // console.log('========444')
          await dispatch('getUserRoleHospitalList')
          // // console.log('========33')
          // 请求配置接口，等待isCheckExamStatus等字段的返回
          await dispatch('getHospitalAppSettings', content.hospitalCode)
          // // console.log('========222')
          await dispatch('settings/getAppConfigSetting', { hospitalCode: content.hospitalCode }, { root: true })
          setHospitalCode(content.hospitalCode)
          // // console.log('========111')
          // !window.g.checkConfigNotApi && await dispatch('settings/getAppConfigSetting', { hospitalCode: content.hospitalCode }, { root: true })
          // 设置用户查询排班管理机房选择的默认机房选项
          // await dispatch('getDefaultCheckRoomTree')
          resolve(content)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 获取用户菜单
  getMenu({
    commit
  }) {
    let params = {
      HospitalCode: '', // this.$store.state.user.hospitalCode,
      SysAppId: sysAppId
    }
    // // console.log('params', params)
    return new Promise((resolve, reject) => {
      // getUserMenuTreeList(params).then(response => {
      getSysUserUserMenuTreeAndRightList(params).then(response => {
        console.log('菜单', response.content.list)
        // var response = {
        //   code: 10000,
        //   Menus: menulistjson
        // };
        if (response && response.code == 10000) {
          // 遍历更新菜单格式
          let menuData = []
          if (response.content && response.content.list) {
            menuData = menuCorrect(response.content.list) // menulistjson //
          }
          if (menuData != null) {
            // 遍历添加本地，菜单隐藏路由配置
            // menuData = menuData.map((item) => {
            //   const asyncMenuIdx = asyncMenu.findIndex((value) => value.path == item.path)
            //   if (asyncMenuIdx >= 0) {
            //     const _child = asyncMenu[asyncMenuIdx].children
            //     asyncMenu.splice(asyncMenuIdx, 1)
            //     item.children = item.children.concat(_child)
            //   }
            //   return item
            // })
            // menuData = menuData.concat(asyncMenu)

            menuData = JSON.stringify(menuData) // .toLowerCase() // 所有的key转换成小写
            // // console.log('menuData', menuData)
            setMenu(menuData)
          }
          router.options.routes = []
          let routes = []
          if (menuData.length > 0) {
            MenuUtils(routes, menuData)
            router.options.routes = Object.assign(
              router.options.routes,
              routes
            )
            router.addRoutes(routes)
          }
          // // console.log("routes:", router.options.routes)
          resolve(response)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取应用配置数据
  getHospitalAppSettings({
    commit
  }, hospitalCode) {
    return new Promise(async (resolve, reject) => {
      await getHospitalAppsettings({ hospitalCode }).then(async res => {
        // console.log('typeof res:', typeof res)
        console.log('getHospitalAppsettings====>', res)
        if (res && res != 'false') {
          // if (process.env.NODE_ENV != 'production' || window.g.isCheckExamStatus) {
          //   res.content.isCheckExamStatus = true
          // }
          commit('SET_APPSETTINGS', res.content)
          // console.log('===setAppSetting===')
          setAppSetting(JSON.stringify(res.content))
        }
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 获取 默认选择机房树数据 医院/院区/部门/科室/机房 数组
  getDefaultCheckRoomTree({
    commit
  }, roomTree) {
    return new Promise(async (resolve, reject) => {
      if (roomTree) {
        commit('SET_ROOMTREE', roomTree)
        resolve(roomTree)
        return
      }
      // // console.log('getDefaultCheckRoomTree', this.state.user.hospitalCode)
      await getCheckroomGroupListTree(this.state.user.hospitalCode).then(async res => {
        // // console.log('getDefaultCheckRoomTree', res)
        commit('SET_ROOMTREE', res)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 获取用户权限医院列表
  getUserRoleHospitalList({
    commit
  }) {
    return new Promise(async resolve => {
      const userRoleHosp = localStorage.getItem('YJYY-HOSPITALUSERROLE')
      if (userRoleHosp) {
        resolve(JSON.parse(userRoleHosp))
        return
      }
      await getSysUserHospitalList().then(res => {
        if (res && res.code === 10000) {
          const role = res.content
          localStorage.setItem('YJYY-HOSPITALUSERROLE', JSON.stringify(role))
          resolve(role)
        }
      })
    })
  },
  // 获取 默认选择机房查询 医院/院区/部门/科室/机房 数组
  getDefaultCheckRoom({
    commit
  }, info) {
    return new Promise(async (resolve, reject) => {
      if (info) {
        commit('SET_DEFAULTROOM', info)
        // // console.warn('getDefaultCheckRoom=>info', info)
        setDefaultCheckRoom(info)
        resolve(info)
        return
      }
      // // console.log('getDefaultCheckRoom', this.state.user.hospitalCode)
      await getDefaultCheckRoomArr(this.state.user.hospitalCode).then(async res => {
        // // console.log('getDefaultCheckRoomArr=>res', res)
        commit('SET_DEFAULTROOM', res)
        // console.warn('getDefaultCheckRoom=>res', res)
        setDefaultCheckRoom(res)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 更新默认选择机房
  resetDefaultCheckRoom({
    commit
  }, info) {
    return new Promise(async (resolve, reject) => {
      commit('SET_DEFAULTROOM', info)
      if (info && info.length > 0) {
        // console.warn('resetDefaultCheckRoom=>info', info)
        setDefaultCheckRoom(info)
      } else {
        // removeDefaultCheckRoom()
      }
      resolve(info)
    })
  },

  // 刷新令牌
  setNewTokenInfo({
    commit
  }, info) {
    const {
      accessToken,
      expires,
      refreshToken
    } = info
    // // // console.log('setNewTokenInfo', info)
    commit('SET_TOKENINFO', info)
    setToken(accessToken)
    setExpires(expires)
    // 登录的时候设置客户端过期时间
    if (refreshToken) {
      setRefreshToken(refreshToken)
      let refreshExpires = Date.parse(new Date()) / 1000 + refreshTime * 24 * 3600 // 换算成秒
      setRefreshExpires(refreshExpires)
    }
  },

  // 退出登录
  logout({
    commit,
    state
  }) {
    return new Promise((resolve) => {
      // console.log('移除各种缓存')
      removeToken() // 移除token
      removeRefreshToken()
      removeUserInfo() // 移除用户信息
      removeRefreshExpires()
      removeExpires()
      removeTags()
      removeMenu()
      // removeDefaultCheckRoom()
      removeAppSetting()
      removeOperateTime()
      commit('RESET_STATE')
      removeLocalStorage('hospitalOptions')
      removeLocalStorage('roomTree')
      localStorage.removeItem('YJYY-HOSPITALUSERROLE')
      setLogoutFlag(true)
      resolve()
    })
  },
  removeLocalInfo({
    commit
  }) {
    return new Promise((resolve) => {
      // removeDefaultCheckRoom()
      removeLocalStorage('hospitalOptions')
      removeLocalStorage('roomTree')
      localStorage.removeItem('YJYY-HOSPITALUSERROLE')
      resolve()
    })
  },

  // remove token
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      removeRefreshToken()
      commit('RESET_STATE')
      resolve()
    })
  },

  // 设置 tags
  resetTags({ commit }, tags) {
    setTags(tags)
    commit('SET_TAGS', tags)
  },
  // 设置 isContinuityNum
  setIsContinuityNum({ commit }, isContinuityNum) {
    setContinuityNum(isContinuityNum)
    commit('SET_ISCONTINUITYNUM', isContinuityNum)
  },
  // 设置 主责
  resetIszz({ commit }, iszz) {
    commit('SET_ISZZYTH', iszz)
  },
  continuationChange({
    commit
  }, type) {
    commit('SET_APPOCONTINUATION', type)
  },

  // 本地登录
  loginLocal({ dispatch, commit }) {
    return new Promise(async (resolve, reject) => {
      const content = {
        accessToken: 'local-login-token',
        expires: Math.floor(new Date().getTime() / 1000) + 18000,
        type: 'local'
      }
      commit('SET_TOKENINFO', content)
      setToken(content.accessToken)
      setExpires(content.expires)
      // 登录的时候设置客户端过期时间
      let refreshExpires = Date.parse(new Date()) / 1000 + refreshTime * 24 * 3600 // 换算成秒
      setRefreshExpires(refreshExpires)
      await dispatch('getInfoLocal')
      await dispatch('getMenuLocal')
      resolve()
    })
  },
  getInfoLocal({
    commit
  }) {
    return new Promise((resolve, reject) => {
      const content = {
        userName: 'local',
        userCode: 'local',
        hospitalId: 'local',
        hospitalCode: 'local',
        hospitalName: 'local',
        id: 'local'
      }
      commit('SET_USERINFO', content)
      const info = JSON.stringify(content)
      setUserInfo(info)
      resolve()
    })
  },
  getMenuLocal({
    commit
  }) {
    return new Promise((resolve, reject) => {
      // 遍历更新菜单格式
      let menuData = menulistjson
      if (menuData != null) {
        // 遍历添加本地，菜单隐藏路由配置
        menuData = menuData.map((item) => {
          const asyncMenuIdx = asyncMenu.findIndex((value) => value.path == item.path)
          if (asyncMenuIdx >= 0) {
            const _child = asyncMenu[asyncMenuIdx].children
            asyncMenu.splice(asyncMenuIdx, 1)
            item.children = item.children.concat(_child)
          }
          return item
        })
        menuData = menuData.concat(asyncMenu)

        menuData = JSON.stringify(menuData)// .toLowerCase() // 所有的key转换成小写
        setMenu(menuData)
      }
      router.options.routes = []
      let routes = []
      if (menuData.length > 0) {
        MenuUtils(routes, menuData)
        router.options.routes = Object.assign(
          router.options.routes,
          routes
        )
        router.addRoutes(routes)
      }
      resolve()
    })
  },
  getHospitalOptions({
    commit,
    dispatch
  }) {
    return new Promise(async (rs, rj) => {
      const params = {}
      // let storage = window.localStorage
      try {
        let hospList = []
        await getSysHospitalGetList(params).then(async res => {
          // // // console.log('设置医院列表数据！！！')
          if (res && res.code === 10000) {
            let storage = window.localStorage
            const roleHosp = await dispatch('getUserRoleHospitalList')
            let resList = res.content.list ? res.content.list : []
            if (roleHosp && !roleHosp.isHasAdminRole) {
              resList = resList.filter(hosp => {
                return roleHosp.sysHospitals.indexOf(hosp.code) >= 0
              })
            }
            hospList = []
            if (resList && resList.length > 0) {
              hospList = resList.map(hosp => {
                return {
                  id: hosp.id,
                  cityName: hosp.cityName,
                  code: hosp.code,
                  county: hosp.county,
                  describe: hosp.describe,
                  name: hosp.name,
                  provinceName: hosp.provinceName
                }
              })
            }
            storage.setItem('hospitalOptions', JSON.stringify(hospList))
          }
        })
        rs(hospList)
      } catch (error) {
        rj()
      }
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
